﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Zoomtel.Service.BIZ;
using Zoomtel.Web.Controllers;
using System.IO;
using Zoomtel.Persist.BIZ;
using Zoomtel.Entity.BIZ;
using System.Xml;

namespace Zoomtel.Web.Areas.Pub.Controllers
{
    [Description("接口测试")]
    public class testController : PubModuleController
    {
        private ItemService _itemService;
        private WechatImgCacheService _imgCacheService;
        WechatLinkRepository _wechatLinkRepository;
       public testController(Zoomtel.Cache.ICacheHandler cache, IHostingEnvironment host,ItemService itemService,WechatImgCacheService imgCacheService,WechatLinkRepository wechatLinkRepository)
        {
            _cache = cache;
            _host = host;
            _itemService = itemService;
            _imgCacheService = imgCacheService;
            _wechatLinkRepository = wechatLinkRepository;
        }


        string APPID = "wxe58b825d6e17e63c";
        string APPSECRET = "c49bfda307d62df7e587bb901f6c655e";
        private Zoomtel.Cache.ICacheHandler _cache;
        private IHostingEnvironment _host;
        private string getAccessToken()
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", APPID, APPSECRET);
            string access_token = _cache.Get<string>("wechat_access_token");
            if (access_token.IsNull())
            {
                string result = Zoomtel.Utils.Helpers.HttpHelper.HttpGet(url);
                var resultModel = JsonConvert.DeserializeObject<JObject>(result);
                access_token = resultModel["access_token"].ToString();
                _cache.Set<string>("wechat_access_token", access_token, 10);

            }
            return access_token;

        }


        private string DownFile(string url)
        {
//获取网站当前根目录
string sWebRootFolder = _host.WebRootPath;
            //保存图片路径
            var savePath = "\\Upload\\download\\";
            //文件名
            string filename = System.IO.Path.GetFileName(url);
            //扩展名
            string extension = System.IO.Path.GetExtension(url);
            savePath = sWebRootFolder + savePath;
            //无夹创建
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            WebClient mywebclient = new WebClient();
            string allpath = savePath + filename;
            //下载文件
            mywebclient.DownloadFile(url, allpath);
            return allpath;
        }

        [AllowAnonymous]
        [HttpGet]
        [Description("wx1")]

        public string weChatCallback(string echostr)
        {
            //string echostr = Request.;
            return echostr;

        }

        private void writeLog(string txt)
        {
           System.IO.File.AppendAllText("c:\\log.txt", txt + "\r\n");


        }


        [AllowAnonymous]
        [HttpPost]
        [Description("wx1")]
        public string weChatCallback()
        {
            //string echostr = Request.;
            
                 //stream.Position = 0;
            StreamReader reader = new StreamReader(Request.Body);
             string text = reader.ReadToEnd();
            writeLog(text);
            if (text.IndexOf("ArticleUrlResult") > 0)
            {
                writeLog("有内容");

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(text);
                var obj = JsonConvert.SerializeXmlNode(doc);

                writeLog("JSON:"+obj);

                var obj1 = JsonConvert.DeserializeObject<JObject>(obj);


                var link = obj1["xml"]["ArticleUrlResult"]["ResultList"]["item"]["ArticleUrl"]["#cdata-section"].ToString();
                writeLog("link:" + link);

                link = link.Replace("http", "https");
                var msgid = obj1["xml"]["MsgID"].ToString();
                writeLog("msgid:" + msgid);

                var model =  _wechatLinkRepository.FindEntity(a => a.msgId == msgid);
                model.linkUrl = link;
                _wechatLinkRepository.Update(model);
            }
         
            return "success";
        }



        [AllowAnonymous]
        [HttpGet]
        [Description("获取微信小程序分享链接")]
        public async Task<IResultModel> getWecharMiniPrgShareUrl(string itemId, string agentID)
        {
        var model=    _wechatLinkRepository.FindEntity(a => a.itemId == itemId && a.agentId == agentID);
            if (model != null)
            {
                return ResultModel.Success(model);
            }

            var itemModel = await _itemService.Get(itemId);
            var imgPath = DownFile(itemModel.PicUrl);

            string miniprogram_appid = "wx7b43afd07dbc20ce";//小程序APPID
            var imgCache = _imgCacheService.Get(itemId);
            if (imgCache == null)
            {

                string uploadResult = UploadLinShiSuCai(imgPath);
                JObject obj = JsonConvert.DeserializeObject<JObject>(uploadResult);
                imgCache = new Entity.BIZ.WechatImgCacheEntity();
                imgCache.mediaId = obj["media_id"].ToString();
                imgCache.url = obj["url"].ToString();
                imgCache.itemId = itemId;
                _imgCacheService.Add(imgCache);
            }




            string path = itemModel.ItemUrl + "&amp;agentid=" + agentID;
            //string imgPath = "https://mmbiz.qpic.cn/mmbiz_png/hEKM8cj9rNQI9luNic04fXLvgIVBAhosfm10xFTG3TfbeiafRsS9uMKQKeREtIRbxqzOb1AP6nGRHxf1fttF97Ng/640?wx_fmt=png&amp;wxfrom=200";


            string content = $"<p><a data-miniprogram-appid=\"{miniprogram_appid}\" data-miniprogram-path=\"{path}\" href=\"\"><img src=\"{imgCache.url}\" alt=\"{itemModel.ItemName}\" ></a></p> ";

            var artice = new JObject();
            artice["title"] = itemModel.ItemName;
            artice["thumb_media_id"] = imgCache.mediaId;
            artice["author"] = "心智数据";
            artice["show_cover_pic"] = 0;
            artice["content"] = content;
            artice["content_source_url"] = "https://agent.xinzhidata.com/Admin/account/login";

            var arr = new JArray();
            arr.Add(artice);

            var PostObj = new JObject();

            PostObj["articles"] = arr;
            string access_token = getAccessToken();

            string postUrl = $"https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={access_token}&type=image";

            string result = Zoomtel.Utils.Helpers.HttpHelper.HttpPost(postUrl, PostObj.ToString(), "application/json");

            var scMdid = JsonConvert.DeserializeObject<JObject>(result)["media_id"];

            //获取永久URL
            //string url3 = $"https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={access_token}";
            //var obj3 = new JObject();
            //obj3["media_id"] = scMdid;
            //result = Zoomtel.Utils.Helpers.HttpHelper.HttpPost(url3, obj3.ToString(), "application/json");

            string url3 = $"https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={access_token}";
            //var obj3 = new JObject();
            //var obj3_1= new JObject();
            //obj3_1["media_id"] = scMdid;
            //obj3["msgtype"] = "mpnews";
            //obj3["msgtype"] = "mpnews";
            List<string> list = new List<string>();
            list.Add("o_RRd6Z1NT1DYVHVp-G_cl3OgVv8");
            list.Add("");
            //obj3["touser"] = list;

            var obj33 = new
            {
                mpnews = new {
                    media_id=scMdid
                },
                msgtype= "mpnews",
                touser=list
            };
            result = Zoomtel.Utils.Helpers.HttpHelper.HttpPost(url3, JsonConvert.SerializeObject(obj33), "application/json");

            var objSendModel = JsonConvert.DeserializeObject<JObject>(result);
            WechatLinkEntity link = new WechatLinkEntity();
            link.id = Guid.NewGuid().ToString("N");
            link.msgId = objSendModel["msg_id"].ToString();
            link.agentId = agentID;
            link.addtime = DateTime.Now;
            link.itemId = itemId;
            link.linkUrl = "";
            _wechatLinkRepository.Insert(link);

                             return ResultModel.Success(link);
  
        }

        [AllowAnonymous]
        [HttpGet]
        [Description("test2")]
        /// <summary>
        /// 上传临时素材
        /// 返回media_id
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string addNews(int userid,string content)
        {
            string access_token = getAccessToken();
            string contetn3 = "<p><a data-miniprogram-appid=\"wx7b43afd07dbc20ce\" data-miniprogram-path=\"pages/detail/detail?id=107&amp;superior_id=659&amp;key=s2t7uzwcg9\" href=\"\"><img src=\"https://mmbiz.qpic.cn/mmbiz_png/hEKM8cj9rNQI9luNic04fXLvgIVBAhosfm10xFTG3TfbeiafRsS9uMKQKeREtIRbxqzOb1AP6nGRHxf1fttF97Ng/640?wx_fmt=png&amp;wxfrom=200\" alt=\"测试测试\" ></a></p> ";
            string url2 = $"https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={access_token}&type=image";
            string contetn1 = "<p>测试是</p><p><mp-miniprogram data-miniprogram-appid=\"wx7b43afd07dbc20ce\" data-miniprogram-path=\"pages/detail/detail?id=107&amp;superior_id=659&amp;key=s2t7uzwcg9\" data-miniprogram-nickname=\"我的认识\" data-miniprogram-avatar=\"https://mmbiz.qpic.cn/mmbiz_png/hEKM8cj9rNQI9luNic04fXLvgIVBAhosfm10xFTG3TfbeiafRsS9uMKQKeREtIRbxqzOb1AP6nGRHxf1fttF97Ng/640?wx_fmt=png&amp;wxfrom=200\" data-miniprogram-title=\"title\" data-miniprogram-imageurl=\"https://mmbiz.qpic.cn/mmbiz_png/hEKM8cj9rNQI9luNic04fXLvgIVBAhosfm10xFTG3TfbeiafRsS9uMKQKeREtIRbxqzOb1AP6nGRHxf1fttF97Ng/640?wx_fmt=jpeg\" data-miniprogram-type=\"card\" data-miniprogram-servicetype=\"0\"></mp-miniprogram></p>";
            //string content2 = "<p><a class=\"weapp_text_link\" data-miniprogram-appid=\"wx7b43afd07dbc20ce\" data-miniprogram-nickname=\"\u3010\u7acb\u5373\u70b9\u51fb\u67e5\u770b\u3011\u6d4b\u4e00\u6d4b\" data-miniprogram-path=\"pages/detail/detail?id=107&amp;superior_id=659&amp;key=s2t7uzwcg9\" data-miniprogram-servicetype=\"\" data-miniprogram-type=\"text\" href=\"\" style=\"display: flex;align-items: center;justify-content: center;width:100%;padding-top:50%;padding-left: 100%;background-image: url(&quot; https://mmbiz.qpic.cn/mmbiz_png/hEKM8cj9rNQI9luNic04fXLvgIVBAhosfm10xFTG3TfbeiafRsS9uMKQKeREtIRbxqzOb1AP6nGRHxf1fttF97Ng/640?wx_fmt=png?wx_fmt=gif&quot;);background-repeat: no-repeat;background-size: contain;background-position: center;\" tab=\"outerlink\" target=\"_blank\" _href=\"\">​&nbsp;<mpchecktext contenteditable=\"false\" id=\"1618458570833_0.7309324416500171\"></mpchecktext></a></p>";
            var artice = new JObject();
            artice["title"] = "测试22222";
            artice["thumb_media_id"] = "WZt5POBar2vxQdBgxCrHh8WZIUG0rY5x24a9kzIxoso";
            artice["author"] = "叶树荣";
            artice["show_cover_pic"] =1;
            artice["content"] = contetn3;
            artice["content_source_url"] = "https://agent.xinzhidata.com/Admin/account/login";

            var arr = new JArray();
            arr.Add(artice);

            var obj = new JObject();

            obj["articles"] = arr;


         string result=   Zoomtel.Utils.Helpers.HttpHelper.HttpPost(url2, obj.ToString(), "application/json");
    


            return result;
        }


     
        /// <summary>
        /// 上传临时素材
        /// 返回media_id
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        private string UploadLinShiSuCai(string imgpath)
        {
            //string imgpath =_host.WebRootPath+$"/1.png";
          

        
            string access_token = getAccessToken();
            string url2 = $"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image";

            //图片转为流
            Image img = new Bitmap(imgpath);
            MemoryStream stream = new MemoryStream();
            img.Save(stream, ImageFormat.Png);
            BinaryReader br = new BinaryReader(stream);
            byte[] data = stream.ToArray();
            stream.Close();



            var boundary = Guid.NewGuid().ToString("N");
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("User-Agent", "KnowledgeCenter");
            client.DefaultRequestHeaders.Remove("Expect");
            client.DefaultRequestHeaders.Remove("Connection");
            client.DefaultRequestHeaders.ExpectContinue = false;
            client.DefaultRequestHeaders.ConnectionClose = true;
            var content = new MultipartFormDataContent(boundary);
            content.Headers.Remove("Content-Type");
            content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
            var contentByte = new ByteArrayContent(data);
            content.Add(contentByte);
            contentByte.Headers.Remove("Content-Disposition");
            contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"1.png\"" + "");
            contentByte.Headers.Remove("Content-Type");
            contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png");
            try
            {
                var result2 = client.PostAsync(url2, content);
                if (result2.Result.StatusCode != HttpStatusCode.OK)
                    throw new Exception(result2.Result.Content.ReadAsStringAsync().Result);
                string jsonstr = result2.Result.Content.ReadAsStringAsync().Result;
               
                return jsonstr;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.InnerException.Message);
            }

        }
    }
}